import webapp2
import jinja2
import os
from google.appengine.ext import db

template_dir = os.path.join(os.path.dirname(__file__),'templates')
jinja_environment = jinja2.Environment(loader =jinja2.FileSystemLoader(template_dir),autoescape= True)


class Art(db.Model):
    title = db.StringProperty(required = True)
    art = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True)
   
   
class Article(db.Model):
    subject = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    created = db.DateTimeProperty(auto_now_add = True) 


class Handler(webapp2.RequestHandler):
    def write(self,*a,**kw):
        self.response.out.write(*a,**kw)
        
    def render_str(self,template,**params):
        t= jinja_environment.get_template(template)
        return t.render(params) 
    
    def render (self,template,**kw):
        self.write(self.render_str(template,**kw))



class MainHandler(Handler):
    def render_front(self,title="",art="",error=""):
        
        arts = db.GqlQuery("SELECT * FROM Art ORDER BY created DESC")        
        self.render("front1.html",title=title,art=art,error=error,arts = arts)

    
    def get(self):
        self.render_front()
    
    def post(self):
        title = self.request.get("title")
        art = self.request.get("art")
        
        if title and art :
            a= Art(title = title, art = art)
            a.put()
            self.redirect("/")

        else:
            error ="ERROR!!"
            self.render_front(title=title,art=art,error=error)
        
        
class BlogHandler(Handler):
    def render_front(self,created=""):     
        articles = db.GqlQuery("SELECT * FROM Article ORDER BY created DESC")        
        self.render("blog.html",articles = articles)
    
    def get(self):
        self.render_front()

            
class NewPostHandler(Handler):
    def render_front(self,subject="",content="",error=""):     
        self.render("newpost.html",subject=subject,content=content,error=error)

    
    def get(self):
        self.render_front()
    
    def post(self):
        subject = self.request.get("subject")
        content = self.request.get("content")
        
        if subject and content :
            article= Article(subject = subject, content = content)
            article.put()
            self.redirect("/blog/newpost/" +str(article.key().id()))

        else:
            error ="ERROR!!"
            self.render_front(subject=subject,content=content,error=error)
            
            
class ArticleHandler(Handler):
    
    def get(self,page):
        article  = Article.get_by_id(int(page)) 
        self.render("article.html",subject=article.subject,content=article.content,created=article.created)




app = webapp2.WSGIApplication([('/', MainHandler),('/blog',BlogHandler),('/blog/newpost',NewPostHandler),('/blog/newpost/([0-9]+)',ArticleHandler)],debug=True)
        
    

    
